import React from 'react';
import {connect} from 'react-redux';
import styles from './style.scss';
import {Button, List, Avatar, message, Modal} from 'antd';
import {withRouter} from 'react-router-dom';
import actions from '../../store/actions/game-box';
import {IMG_DOMAIN} from 'utils/constants';
const confirm = Modal.confirm;

class GameBox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      showEditor: false,
      selectItem: {}
    };
  }
  async componentWillMount() {
    const {dispatch} = this.props;
    dispatch(actions.getGameList());
  }

  showConfirm(item) {
    this.setState({
      selectItem: item
    });
    const self = this;
    confirm({
      title: '确认删除这个游戏吗?',
      content: '删除后将无法恢复，如果不确认该配置是否会再次使用，可以先下架',
      okText: '确认',
      cancelText: '取消',
      onOk() {
        return new Promise(async (resolve, reject) => {
          const {dispatch} = self.props;
          const res = await dispatch(actions.deleteById(self.state.selectItem.id));
          if (res.code === '0') {
            resolve();
            dispatch(actions.getGameList());
          } else {
            reject();
          }
        }).catch(() => message.error('删除失败！'));
      },
      onCancel() {}
    });
  }

  showEditor(item, type = 'add') {
    if (item) {
      let data = {id: item.id, type};
      let path = {
        pathname: '/gameBox/editor',
        data
      };
      this.props.history.push(path);
    } else {
      this.props.history.push('/gameBox/editor');
    }
  }

  async switchStatus(item) {
    const {dispatch} = this.props;
    const res = await dispatch(
      actions.editGame(item.id, {
        status: item.status === 0 ? 1 : 0
      })
    );
    if (res.code === '0') {
      await dispatch(actions.getGameList());
      message.info('操作成功！');
    }
  }

  buildActions(item) {
    return [
      <a
        onClick={() => {
          this.showEditor(item, 'edit');
        }}
        role="presentation"
      >
        编辑查看
      </a>,
      <a
        onClick={() => {
          this.switchStatus(item);
        }}
        role="presentation"
      >
        {item.status === 0 ? '发布' : '下架'}
      </a>,
      <a
        onClick={() => {
          this.showConfirm(item);
        }}
        role="presentation"
      >
        删除
      </a>
    ];
  }

  render() {
    let {list} = this.props.gameBoxState.list;
    return (
      <div className={styles.wrap}>
        <div className={styles.handlers}>
          <Button
            type="primary"
            onClick={() => {
              this.showEditor();
            }}
          >
            添加
          </Button>
        </div>
        <List
          style={{marginTop: 42}}
          itemLayout="horizontal"
          dataSource={list}
          renderItem={(item) => (
            <List.Item actions={this.buildActions(item)}>
              <List.Item.Meta
                avatar={<Avatar src={`${IMG_DOMAIN}${item.icon}`} />}
                title={<a>{item.name}</a>}
                description={item.slogan}
              />
            </List.Item>
          )}
        />
      </div>
    );
  }
}

function select(state) {
  return state;
}

export default withRouter(connect(select)(GameBox));
